package com.conner.file_amend;

import java.util.HashMap;

import com.conner.file_types.Files;
import java.util.ArrayList;

public class FileCleaner {
	
	HashMap<Integer,String> errorList = new HashMap<Integer,String>();
	
	/*
	 * Verify Marks to cleanup
	 */
	public HashMap<Integer,String> startCleanup(Files f){
		String lines[] = f.getInformation().split("\\r?\\n");
        errorList = new HashMap<Integer,String>();
		for(int i = 0; i < lines.length; i++){
			String temp = lines[i];
			temp = itrim(temp);
			if(!temp.equals(lines[i])){
				errorList.put(errorList.size()-1, "Extra Middle spaces found on line " + (i+1));
			}
			String temp2 = temp;
			temp2 = ltrim(temp2);
			if(!temp2.equals(temp)){
				errorList.put(errorList.size()-1, "Extra Beginning spaces found on line " +  (i+1));
			}
			String temp3 = temp2;
			temp3 = rtrim(temp3);
			if(!temp3.equals(temp2)){
				errorList.put(errorList.size()-1, "Extra End spaces found on line " +  (i+1));
			}
            ArrayList charErrors = checkFileChars(temp3);
            for(Object c:charErrors){
                errorList.put(errorList.size()-1, "Invalid Character('"+ c +"') found on line " + (i+1));
            }
		}
		return errorList;
	}
	
	
	
	/*
	 * Actual Cleanup
	 */
	//Remove all excess spaces Left Right and Inbetween
	public String scanForSpaces(String fileLine){
		String tempLine = fileLine;
		fileLine = itrim(rtrim(ltrim(fileLine)));
		return fileLine;
	}
	public String ltrim(String fileLine) {
        return fileLine.replaceAll("^\\s+", "");
    }
	public String rtrim(String fileLine) {
        return fileLine.replaceAll("\\s+$", "");
    }
	public String itrim(String fileLine) {
        return fileLine.replaceAll("\\b\\s{2,}\\b", " ");
    }
	
	
	//Check for improper Chars ~ returns string array with line and character
	public  ArrayList checkFileChars(String line){
        ArrayList chars = new ArrayList();
		for(int i = 0; i < line.length(); i++)
			if(line.charAt(i) < 040 || line.charAt(i) > 176)
				chars.add(line.charAt(i));
		return chars;
	}
}
